package server.core;

import javax.servlet.*;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/*
实现过滤器链链的类,调用该类的doFilter方法会调用第一个过滤器的doFilter方法,由该过滤器决定是否要调用下一个过滤器的doFilter,
当最后一个过滤器调用doFilter方法时,会调用servlet的service方法
*/
/*
2023/2/27 该类内容全部写完,后续直接使用,无需修改
by cyl
 */
public final class ApplicationFilterChain implements FilterChain {
    private List<FilterConfig> filters = new ArrayList<>();
    private Iterator<FilterConfig> iterator = null;
    //要过滤的Servlet对象
    private Servlet servlet = null;

    public void addFilter(ApplicationFilterConfig filterConfig) {
        filters.add(filterConfig);
    }

    public void setServlet(Servlet servlet) {
        this.servlet = servlet;
    }

    //实现FilterChain接口----------------------------------------------------------------------------
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse) throws IOException, ServletException {
        if (iterator == null)
            iterator = filters.iterator();
        //依次执行每个过滤器的doFilter方法
        if (iterator.hasNext()) {
            ApplicationFilterConfig filterConfig = (ApplicationFilterConfig)(iterator.next());
            Filter filter = null;
            try {
                filter = filterConfig.getFilter();
                filter.doFilter(servletRequest, servletResponse, this);
                return;
            } catch (Throwable t) {
                throw new ServletException(t);
            }

        }
        //所有过滤器都执行无误,执行service方法
        try {
            servlet.service(servletRequest, servletResponse);
        } catch (Throwable t) {
            throw new ServletException(t);
        }
    }
}
